Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Class → OOPS Introduction

Python Class

OOPS Introduction

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming paradigm that organizes code around "objects" rather than "actions" and "data" rather than logic. It's a powerful approach for building complex and maintainable software. Python is a highly object-oriented language, making it ideal for exploring OOP concepts. The core of OOP revolves around four fundamental principles: Abstraction: Hiding complex implementation details and showing only essential information to the user. Think of a car – you drive it without needing to understand the intricacies of its engine. Encapsulation: Bundling data (attributes) and methods (functions) that operate on that data within a single unit (a class). This protects data integrity and promotes modularity. Inheritance: Creating new classes (child classes) based on existing classes (parent classes), inheriting their attributes and methods and extending or modifying them. This promotes code reusability. Polymorphism: The ability of objects of different classes to respond to the same method call in their own specific way. This allows for flexible and extensible code. Let's explore these concepts through Python examples focusing on class definitions:

1. Defining a Simple Class

Defining a class in python class Dog: # Class definition starts with 'class' followed by the class name (conventionally capitalized) def __init__(self, name, breed): # Constructor (__init__) initializes object attributes self.name = name # 'self' refers to the instance of the class self.breed = breed def bark(self): # Method to define dog's behaviour print("Woof!") def describe(self): #Method to describe the dog print(f"My name is {self.name} and I'm a {self.breed}.") my_dog = Dog("Buddy", "Golden Retriever") # Creating an instance (object) of the Dog class my_dog.bark() #Calling a method my_dog.describe()

Output

Woof! My name is Buddy and I'm a Golden Retriever.

2. Encapsulation and Data Hiding (using name mangling)

We can control access to attributes using name mangling (prefixing with double underscores `__`). While not strictly "private" in Python, it signals an intention to restrict direct access.
Python encapsulation example class BankAccount: def __init__(self, account_number, balance): self.account_number = account_number self.__balance = balance # Name mangling suggests this should be treated as private def deposit(self, amount): self.__balance += amount def withdraw(self, amount): if self.__balance >= amount: self.__balance -= amount else: print("Insufficient funds!") def get_balance(self): #Provides controlled access to the balance return self.__balance my_account = BankAccount("12345", 1000) my_account.deposit(500) print(my_account.get_balance()) # Accessing balance through a method #print(my_account.__balance) #Trying to access directly (will likely cause an error or access mangled name)

Output

1500

3. Inheritance

Python inheritance example class Animal: # Parent class def __init__(self, name): self.name = name def speak(self): print("Generic animal sound") class Cat(Animal): # Child class inheriting from Animal def speak(self): print("Meow!") class Dog2(Animal): #Another Child Class def speak(self): print("Woof!") my_cat = Cat("Whiskers") my_dog = Dog2("Fido") my_cat.speak() my_dog.speak()

Output

Meow! Woof!
This example shows `Cat` and `Dog2` inheriting from `Animal` and overriding the `speak` method, demonstrating polymorphism.

4. Polymorphism

Python Polymorphism example class Shape: def area(self): pass # Abstract method (no implementation) class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14159 * self.radius**2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side**2 shapes = [Circle(5), Square(4)] for shape in shapes: print(shape.area()) # Polymorphism: area() behaves differently for each shape

Output

78.53975 16

Additionally

Using type() to Create Classes Dynamically

Did you know that classes themselves are objects in Python? They are instances of a metaclass (by default, type). This means you can actually create classes programmatically using the type() function. The type() function can be used in two ways: ⮞ type(object): Returns the type of an object. ⮞ type(name, bases, dict): Creates a new type object (a class).
Using type() to Create Classes Dynamically in python def __init__(self, name, breed): self.name = name self.breed = breed def bark(self): print("Woof!") Dog = type("Dog", (), {"__init__": __init__, "bark": bark}) another_dog = Dog("Lucy", "Poodle") print(f"{another_dog.name} is a {another_dog.breed}") another_dog.bark()

Output

Lucy is a Poodle Woof!
Explanation: The first argument "Dog" is the name of the class. The second argument () is a tuple specifying the base classes (inheritance). Here, it's empty, meaning Dog inherits from object (the default base class). The third argument {"__init__": __init__, "bark": bark} is a dictionary where the keys are the method names (as strings) and the values are the corresponding function objects. This approach is less common for defining regular classes but is very powerful for metaprogramming and creating classes dynamically based on certain conditions.

Tutorials